<template>
  <form class="validate-form-container">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
import mitt from 'mitt' // 引入事件监听器 第三方库
// type 类型别名
type ValidateFunc = () => boolean
export const emitter = mitt()
export default defineComponent({
  emits: ['form-submit'],
  setup (props, context) {
    let funcArr: ValidateFunc[] = []
    // 提交时触发用于验证
    const submitForm = () => {
      // map() 方法返回一个新数组，数组中的元素为原始数组元素调用函数处理后的值
      // every方法用于检测数组所有元素是否都符合指定条件,如果数组中检测到有一个元素不满足，则整个表达式返回 false
      const result = funcArr.map(func => func()).every(result => result)
      // 向外(父组件)触发名为form-submit的事件
      context.emit('form-submit', result)
    }
    const callback = (func: any | ValidateFunc) => {
      funcArr.push(func)
    }
    // 接受子组件form-item-created监听事件(父子组件信息通讯)
    emitter.on('form-item-created', callback)
    onUnmounted(() => {
      // 删除监听
      emitter.off('form-item-created', callback)
      funcArr = []
    })
    return {
      submitForm
    }
  }
})
</script>

<style>

</style>
